$(document).ready(function(){

	var region_code = $("#curr_region_code").val();
	var hardware_code = $("#curr_hardware_code").val();
	var content = {
		"desc": "desc",
		"desc_en": "desc_en",
		"region_code":region_code,
		"hardware_code":hardware_code,
		"sys_version_name": "V0.0.0",
		"version_package": {
			"V0.9.1": {
				"is_forced": false,
				"is_full": false,
				"addr": "http://inspero-ata.oss",
				"hash": "11:22:22:a1:3e:ad",
				"length": "123123"
			},
			"V1.0.1": {
				"is_forced": false,
				"is_full": false,
				"addr": "http://inspero-ata.oss",
				"hash": "11:22:22:a1:3e:ad",
				"length": "123123"
			}
		}
	};
	var config = {};

	var old_config = {};

	// ajax 获取测试数据
	$.ajax({
		type: 'GET',
		// 本地调试用localhost
		// 联调需要注释掉 data

		url: '/vinci/device/otaconfig/getOTATestConfig',
		data : {
			region_code: region_code,
			hardware_code: hardware_code,
		},
		//url: 'http://localhost:2000/ff',
		contentType: "application/json;charset=utf-8",
		//data: JSON.stringify(config),
		dataType: 'json',
		success: function(data){
			console.log("22222");
			console.log(data);
			// 转换赋值方法
			if (data.content==undefined) {
				data.content = {
					"desc": "",
					"desc_en": "",
					"sys_version_name": "",
					"version_package": {}
				};
			};
			var str = JSON.stringify(data.content);
			var num = JSON.stringify(data.status);
			config.content = $.parseJSON(str);
			config.status = $.parseJSON(num);
			config.content.region_code = region_code;
			config.content.hardware_code = hardware_code;
			old_config.content = $.parseJSON(str);
			old_config.status = $.parseJSON(num);
			console.log(config.status == old_config.status);
			console.log(JSON.stringify(config.content) == JSON.stringify(old_config.content));
			console.log(config == old_config);
			renderConfig(config.content);
		},
		error:function(err){
			console.log("333333");
			console.log(err);
			//renderConfig(content);
		}
	});

	// 渲染 config 数据到 html 中
	function renderConfig(object){
		$(".content").remove();
		$("#desc").val(object.desc);
		$("#desc_en").val(object.desc_en);
		var sys_version_name = object.sys_version_name;
		sys_version_name = sys_version_name.split('.');
		sys_version_name[0] = sys_version_name[0].slice(1);
		$(".sys-version-name-num").eq(0).val(sys_version_name[0]);
		$(".sys-version-name-num").eq(1).val(sys_version_name[1]);
		$(".sys-version-name-num").eq(2).val(sys_version_name[2]);
		$("#sys_version_name_save").click();
		$(".error_version_show").text("");
		$("#current_version_show").text("目标版本：" + object.sys_version_name);
		$.each(object.version_package, function(name, value){
			var newRow =
					"<tr class='content'>" +
					"<td>" + name + "</td>" +
					"<td>" + object.version_package[name].is_forced + "</td>" +
					"<td>" + object.version_package[name].is_full + "</td>" +
					"<td>" + object.version_package[name].addr + "</td>" +
					"<td>" + object.version_package[name].hash + "</td>" +
					"<td>" + object.version_package[name].length + "</td>" +
					"<td>" +
					'<button type="button" class="btn-primary btn change_version">修改</button>' +
					'<button type="button" class="btn-danger btn delete-father" data-toggle="modal" data-target="#myModal">删除</button>' +
					"</td>" +
					"</tr>";
			$(".table-package").append(newRow);
		});

		// 删除展示的数据，同时删除config.version_package中的相关对象
		var version_Num,is_forced,is_full,addr,hash,length;
		$(".delete-father").click(function(){
			var $first = $(this).parent().parent().children().first();
			version_Num = $first.text();
			$(".delete_version").text("确认删除");
			$(".modal-body").text("确认删除 " + version_Num + " 对象的数据吗？");
			$(".delete_version").unbind();
			$(".delete_version").click(function(){
				$.each(config.content.version_package, function(name, value){
					if (name == version_Num) {
						var id = config.content.version_package[name].id;

						$.ajax({
							type: 'POST',
							url: '/vinci/device/otaconfig/delVersionPackage',
							//contentType: "application/json;charset=utf-8",
							data: { 'id': id},
							dataType: 'json',
							success: function(data){
								console.log(data);
								console.log(22);
							},
							error: function(err){
								console.log(err);
								console.log(333);
							}
						})
						delete config.content.version_package[name];
						console.log(config.content);
					}
				})
				renderConfig(config.content);
			});
		})


		// 修改展示的数据，同时修改config.version_package中的相关数据
		var versionPackageChangeIndex = 0;
		$(".change_version").click(function(){
			var $first = $(this).parent().parent().children().first();
			var $isForced = $first.next();
			var $isFull = $isForced.next();
			version_Num = $first.text();
			is_forced = $isForced.children().val();
			is_full = $isFull.children().val();
			if (versionPackageChangeIndex==0) {
				versionPackageChangeIndex = 1;
				$(".change_version").attr("disabled","true");
				$(this).removeAttr("disabled");
				$(this).text("完成修改");
				$first.parent().addClass("important");
				$isForced.text("");
				$isFull.text("");
				var newSelect = '<select name="" class="form-control">' +
						'<option value="false">false</option>' +
						'<option value="true">true</option>' +
						'</select>';
				$($isForced).append(newSelect);
				$($isFull).append(newSelect);
			} else {
				versionPackageChangeIndex = 0;
				$(this).text("修改");
				$(".change_version").removeAttr("disabled");
				$.each(config.content.version_package, function(name, value){
					if (name == version_Num) {
						value.is_forced = is_forced;
						value.is_full = is_full;
					};
				});
				$isForced.children().remove();
				$isFull.children().remove();
				$isForced.text(is_forced);
				$isFull.text(is_full);
				$first.parent().removeClass("important");
			};

		})
	};

	// 强制首先输入目标版本号
	//$(".button").attr("disabled","true");

	var addr = new Array();
	// 验证当前版本输入格式
	var checkNum = /^[0-9]{1,2}$/;
	var checkNumStatus = [1, 1, 1, 1, 1, 1, 1];
	$(".sys-version-name-num").blur(function(){
		var checkStatus = 0;
		var num = $(this).val();
		var i = $(this).index();
		if (checkNum.test(num)){
			checkNumStatus[i] = 0;
		} else {
			checkNumStatus[i] = 1;
			$(this).focus();
		}
		for( var i = 1; i<=5; i+=2 ) {
			checkStatus += checkNumStatus[i];
		}
		console.log(checkStatus);
		if (checkStatus == 0) {
			$(".error_version_show").text("").removeClass("important");
			$("#sys_version_name_save").removeAttr("disabled");
		} else {
			$(".error_version_show").text("请输入正确的目标版本号！").addClass("important");
			$("#sys_version_name_save").attr("disabled","true");
		}
	})

	//地域硬件版本号有变动,就刷新页面
	$("#curr_region_code,#curr_hardware_code").change(function() {
		var region_code = $("#curr_region_code").val();
		var hardware_code = $("#curr_hardware_code").val();
		window.location.href = "/vinci/device/otaconfig/index?region_code="+region_code+"&hardware_code="+hardware_code;
	})

	// 提交目标版本号
	$("#sys_version_name_save").click(function(){
		var versionNum = new Array();
		$(".btn:not(.increase-mac)").removeAttr("disabled");
		$(".sys-version-name-num").attr("disabled","true");
		$("#desc").attr("disabled","true");
		$("#desc_en").attr("disabled","true");
		$(".sys-version-name-num").each(function(i, num){
			versionNum[i] = $(num).val();
		})
		var txt = "目标版本：V "+versionNum[0]+"."+versionNum[1]+"."+ versionNum[2];
		addr[0] = "V" + versionNum[0] + "." + versionNum[1] + "." + versionNum[2];
		$("#current_version_show").text(txt);
		config.content.sys_version_name = addr[0];
		config.content.desc = $("#desc").val();
		config.content.desc_en = $("#desc_en").val();
	})
	$("#sys_version_name_change").click(function(){
		$(".sys-version-name-num").removeAttr("disabled");
		$("#desc").removeAttr("disabled");
		$("#desc_en").removeAttr("disabled");
		$(".btn").attr("disabled","true");
	})

	// is_full 被修改
	$("#is_full").change(function(){
		if ($("#is_full").val() == "false") {
			var versionNum = new Array();
			$(".old-sys-version-name-num").each(function(i, num){
				versionNum[i] = $(num).val();
			});
			addr[1] = "V" + versionNum[0] + "." + versionNum[1] + "." + versionNum[2] + "_";
			addr[2] = addr[1] + addr[0];
			$("#addr").val(addr[2]);
		}else{
			addr[1] = "all_";
			addr[2] = addr[1] + addr[0];
			$("#addr").val(addr[2]);
		};
	})

	// 验证历史版本号输入格式
	var increaseAbleIndex = [1,1,1,1,1,1];
	$(".old-sys-version-name-num").blur(function(){
		var num = $(this).val();
		var i = $(this).index();
		switch (i) {
			case 1:i=0;break;
			case 3:i=1;break;
			case 5:i=2;break;
			default:alert("?");break;
		}
		if (checkNum.test(num)) {
			increaseAbleIndex[i] = 0;
			$('#error_info').text("");
		} else {
			increaseAbleIndex[i] = 1;
			$(this).focus();
			$('#error_info').text("请输入正确的版本号！");
		}
		// 自动填写addr内容
		if ($("#is_full").val() == "false") {
			var versionNum = new Array();
			$(".old-sys-version-name-num").each(function(i, num){
				versionNum[i] = $(num).val();
			});
			addr[1] = "V" + versionNum[0] + "." + versionNum[1] + "." + versionNum[2] + "_";
			addr[2] = addr[1] + addr[0];
			$("#addr").val(addr[2]);
		}else{
			addr[1] = "all_";
			addr[2] = addr[1] + addr[0];
			$("#addr").val(addr[2]);
		};
		addr[1] = "V" + versionNum[0] + "." + versionNum[1] + "." + versionNum[2] + "_";
		addr[2] = addr[1] + addr[0];
		$("#addr").val(addr[2]);
		increaseAble();
	})

	// 验证addr格式
	$("#addr").blur(function(){
		if ($("#is_full").val() == "false") {
			var checkAddr = /^V[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}_V[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}$/;
			if (checkAddr.test($(this).val())) {
				$("#error_info").text("");
				increaseAbleIndex[3] = 0;
			} else {
				$("#error_info").text("请输入正确的addr！");
				increaseAbleIndex[3] = 1;
				$(this).focus();
			};
		}else{
			var checkAddr = /^all_V[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}$/;
			if (checkAddr.test($(this).val())) {
				$("#error_info").text("");
				increaseAbleIndex[3] = 0;
			} else {
				$("#error_info").text("请输入正确的addr！");
				increaseAbleIndex[3] = 1;
				$(this).focus();
			};
		};
		increaseAble();
	})

	// 验证hash
	$("#hash").blur(function(){
		var checkHash = /^\w{32}$/;
		if (checkHash.test($(this).val())) {
			$("#error_info").text("");
			increaseAbleIndex[4] = 0;
		} else {
			$("#error_info").text("请输入正确的hash！");
			increaseAbleIndex[4] = 1;
			$(this).focus();
		};
		increaseAble();
	})

	// 验证length
	$("#length").blur(function(){
		var checkLength = /^\d+$/;
		if (checkLength.test($(this).val())) {
			$("#error_info").text("");
			increaseAbleIndex[5] = 0;
		} else {
			$("#error_info").text("请输入正确的length！");
			increaseAbleIndex[5] = 1;
			$(this).focus();
		};
		increaseAble();
	})

	// increase_package 是否可点
	function increaseAble(){
		var index = 0;
		$.each(increaseAbleIndex, function(idx, obj){
			index += obj;
		})
		if (index==0) {
			$("#increase_version").removeAttr("disabled");
		} else {
			$("#increase_version").attr("disabled","true");
		}
		console.log(index);
	}


	// 新增version_package对象按钮
	$("#increase_version_package").click(function(){
		$(".input-card").slideDown();
	})

	// 增加数据到json对象，同时重新渲染页面
	$("#increase_version").click(function(){
		$(".input-card").slideUp();
		var version = "V" + $("#version_num_1").val() + "." + $("#version_num_2").val() + "." + $("#version_num_3").val();
		var is_forced = $("#is_forced").val();
		var is_full = $("#is_full").val();
		var addr = $("#pre_addr").text() + $("#addr").val() + ".zip";
		var hash = $("#hash").val();
		var length = $("#length").val();
		config.content.version_package[version] = {
			"is_forced": is_forced,
			"is_full": is_full,
			"addr": addr,
			"hash": hash,
			"length": length
		};
		resetInputCard();
		console.log(config.content);
		renderConfig(config.content);
	})
	// 取消增加
	$("#cancel_increase_version").click(function(){
		$(".input-card").slideUp();
		$("tr").removeClass("important");
		resetInputCard();
	})
	// input 卡片重置
	function resetInputCard(){
		$(".form-horizontal")[0].reset();
		increaseAbleIndex = [1,1,1,1,1,1];
		increaseAble();
	}

	// 提交config测试
	$("#finish").click(function(){
		$(".modal-title").text("提交确认");
		$(".modal-body").text("确认提交测试版本数据？");
		$(".delete_version").text("确认提交");
		$(".delete_version").unbind();
		$(".delete_version").click(function(){
			//config.content = content;
			console.log(content);
			$.ajax({
				type: 'POST',
				// 本地调试用localhost
				url: '/vinci/device/otaconfig/addOrUpdateOTATestConfig',
				//url: 'http://localhost:2000/ff',
				contentType: "application/json;charset=utf-8",
				data: JSON.stringify(config.content),
				dataType: 'json',
				success: function(data){
					console.log("22222");
					console.log(data);
					old_config = config;
					alert("提交成功！");
					$("#commit_status").text("提交成功！");
					setTimeout(function(){
						location.reload();
					},1000);
				},
				error:function(err){
					console.log("333333");
					console.log(err);
					$("#commit_status").text("提交失败！");
				}
			})
		})
	});

	// 发布 config
	$("#publish").click(function(){
		console.log(config);
		console.log(old_config);
		//console.log(config == old_config);
		if(JSON.stringify(config) == JSON.stringify(old_config)) {
			$(".modal-title").text("发布确认");
			$(".modal-body").text("确认发布 config 数据到服务器？");
			$(".delete_version").text("确认发布");
			$("#myModal").modal();
			$(".delete_version").unbind();
			$(".delete_version").click(function(){
				var configId = config.content.id;
				console.log(configId);
				$.ajax({
					type: 'POST',
					url: '/vinci/device/otaconfig/testConfigToDeploy',
					//contentType: "application/json;charset=utf-8",
					data: { "configId": configId,region_code:region_code,hardware_code:hardware_code },
					dataType: 'json',
					success: function(data){
						console.log(22);
						console.log(data);
						$("#commit_status").text("发布成功！");
						//window.open('history.html');
					},
					error: function(err){
						console.log(33);
						console.log(err);
						$("#commit_status").text("发布失败！")
					}
				})
			});
		} else {
			$("#commit_status").text("请先提交修改！");
		}

	})

	// 查看历史config
	 $("#history").click(function(){
	 	window.open('/vinci/device/otaconfig/configHistory?region_code='+region_code+"&hardware_code="+hardware_code);
	 })

	// 添加 mac 地址
	$(".increase-mac").click(function(){
		var mac = $(".mac-addr").val();
		$.ajax({
			type: 'POST',
			url: '/vinci/device/otaconfig/addMac',
			//contentType: "application/json;charset=utf-8",
			data: { "macAddr": mac },
			dataType: 'json',
			success: function(data){
				console.log("mac success");
				console.log(data);
				$(".mac-status").text("IMEI 添加成功！");
			},
			error: function(err){
				console.log("mac fail");
				console.log(err);
				$(".mac-status").text("IMEI 添加失败！");
			}
		})
		$(this).attr("disabled","true");
		i = 0;
		$(".mac-list").remove();
		$(".all-mac").click();
	})

	// 校验mac地址
	$(".mac-addr").blur(function(){
		//var macReg = /^([0-9a-fA-F][0-9a-fA-F]:){5}[0-9a-fA-F]{2}$/;
		var macReg = /^[0-9]{15}$/;
		var mac = $(this).val();
		if (macReg.test(mac)) {
			$(".increase-mac").removeAttr("disabled");
			$(".mac-status").text("");
		} else {
			$(".mac-status").text("请输入正确的IMEI！");
		}
	})

	// 查看所有 mac 并删除
	var i = 0;

	$(".all-mac").click(function(){
		if (i==0) {
			$(".all-mac").text("收起");
			$(".mac-table").show()
			$.ajax({
				type: 'GET',
				url: '/vinci/device/otaconfig/getTestMacs',
				dataType: 'json',
				success: function(data){
					console.log(data);
					console.log("获取mac成功");
					$.each(data.content, function(n, value){
						var newRow =
								"<tr class='mac-list'>" +
								"<td>" + value.id + "</td>" +
								"<td>" + value.mac + "</td>" +
								"<td>" +
								"<button class='change-mac mac-button btn btn-success' type='button'>修改IMEI</button>" +
								"<button class='delete-mac mac-button btn btn-danger' type='button'>删除IMEI</button>" +
								"</td>"
						"</tr>";
						$('.mac-table').append(newRow);
					});
					$(".delete-mac").click(function(){
						var macId = $(this).parent().prev().prev().text();
						$(this).parent().parent().remove();
						$.ajax({
							type: 'POST',
							url: '/vinci/device/otaconfig/delMac',
							data: { "macId": macId },
							dataType: 'json',
							success: function(data){
								console.log("删除IMEI成功");
							},
							error: function(err){
								console.log("删除IMEI失败");
							}
						})
					});
					var changeIndex = 0;
					$(".change-mac").click(function(){

						if (changeIndex == 0) {
							$(this).text("确认修改");
							$(".change-mac").attr("disabled", "true");
							var macId = $(this).parent().prev().prev().text();
							var mac = $(this).parent().prev().text();
							$(this).parent().prev().remove();
							$("<td><input type='text' class='mac-input' /></td>").insertBefore($(this).parent());
							$(".mac-input").val(mac);

							// 验证输入mac
							$(".mac-input").blur(function(){
								var macReg = /^[0-9a-fA-F]{15}$/;
								var mac = $(this).val();
								if (macReg.test(mac)) {
									$(this).parent().next().children().removeAttr("disabled");
									$(".mac-status").text("");
									//console.log($(this).val());
								} else {
									$(".mac-status").text("请输入正确的IMEI！");
								}
							});

							changeIndex = 1;
						} else {
							$(this).text("修改IMEI");
							changeIndex = 0;
							var macId = $(this).parent().prev().prev().text();
							var mac = $(this).parent().prev().children().val();
							console.log(mac);
							var json = {
								"id": macId,
								"mac": mac
							};
							$(".change-mac").removeAttr("disabled");
							$(this).parent().prev().remove();
							$("<td></td>").insertBefore($(this).parent());
							$(this).parent().prev().text(mac);
							$.ajax({
								type: 'POST',
								url: '/vinci/device/otaconfig/updateMac',
								contentType: "application/json;charset=utf-8",
								data: JSON.stringify(json),
								dataType: 'json',
								success: function(data){
									console.log("修改IMEI成功");
								},
								error: function(err){
									console.log("修改IMEI失败");
									console.log()
								}
							});

						}
					});


				},
				error: function(err){
					console.log("获取IMEI失败");
				}
			});
			i = 1;
		} else {
			$(".mac-table").hide(1);
			$(".mac-list").remove();
			$(".all-mac").text("查看所有IMEI");
			i = 0;
		}

	})

	// 根据国家不同 使用不同的addr
	switch($("#curr_region_code").val()){
		case "US": $("#pre_addr").text("http://inspero-ota.oss-cn-beijing.aliyuncs.com/intl/ota_");break;
		case "CN": $("#pre_addr").text("http://inspero-ota.oss-cn-beijing.aliyuncs.com/ota_");break;
		case "BD": $("#pre_addr").text("http://inspero-ota.oss-cn-beijing.aliyuncs.com/baidumusic/ota_");break;
		default: break;
	}
})